package com.fengke.portal.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fengke.portal.config.HostConfig;
import com.fengke.schedule.tencent.AccessTokenRefreshSchedule;
import com.fengke.util.ContextManager;
import com.fengke.util.LoggerFactory;

/**
 * Application Lifecycle Listener implementation class SystemListener
 *
 */
public class SystemListener implements ServletContextListener, ServletContextAttributeListener {
	private Logger logger = LoggerFactory.getLogger(SystemListener.class);
    /**
     * Default constructor. 
     */
    public SystemListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent event) {
    	logger.info("初始化侦听器开始！");
    	ServletContext context = event.getServletContext();
    	WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    	ContextManager.setContext(ctx);
    	HostConfig hostConfig = (HostConfig) ctx.getBean("hostConfig");
    	AccessTokenRefreshSchedule accessTokenRefreshSchedule = (AccessTokenRefreshSchedule) ctx.getBean("accessTokenRefreshSchedule");
    	context.setAttribute("hostConfig", hostConfig);
    	// 启动服务时，刷新access_token
    	accessTokenRefreshSchedule.refresh();
    	logger.info("初始化侦听器结束！");
    }

	/**
     * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
     */
    public void attributeAdded(ServletContextAttributeEvent scab) {
        // TODO Auto-generated method stub
    }

	/**
     * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
     */
    public void attributeReplaced(ServletContextAttributeEvent scab) {
        // TODO Auto-generated method stub
    }

	/**
     * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
     */
    public void attributeRemoved(ServletContextAttributeEvent scab) {
        // TODO Auto-generated method stub
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
    }
	
}
